#ifndef SQLITEUTILS_H
#define SQLITEUTILS_H
#include <QSqlError>
#include <QSqlQuery>
#include <QSqlRecord>
#include "qsqlquery.h"
#include <OrmBase.h>
#include <QObject>
#include <QSqlDatabase>

///
/// 连接数据库
///
class DatabaseManager  : public QObject
{
    Q_OBJECT
public:
    explicit DatabaseManager(QObject *parent = nullptr);
    //初始化sqlite
    bool initDatabase(const QString &dbPath);

    void setQuery(const QSqlQuery &newQuery);

    //单例模式
    static DatabaseManager& instance() {
        static DatabaseManager instance;
        return instance;
    }

    bool createTables(const QString &sql);

    //插入
    bool insert(const OrmBase &obj);
    //更新
    bool update(const OrmBase &obj, const QString &whereClause);
    //删除
    bool remove(const OrmBase &obj, const QString &whereClause);
    //生成表
    bool createTableFromClass(const OrmBase &obj);
    //泛型查询
    template<typename T>
    QList<T*> select(
        const QString &where = "",
        const QString &orderBy= "",
        const QString &limit= "")
    {
        QList<T*> results;
        T tempObj;
        QString sql = QString("SELECT * FROM %1")
                          .arg(tempObj.tableName());
        if (!where.isEmpty()) {
            sql += " WHERE " + where;
        }
        if (!orderBy.isEmpty()) {
            sql += " ORDER BY " + orderBy;
        }
        if (!limit.isEmpty()) {
            sql += " LIMIT " + limit;
        }
        QSqlQuery selectQuery(db);
        if (!selectQuery.exec(sql)) {
            qDebug() << "查询失败:" << selectQuery.lastError().text();
            return results;
        }

        while (selectQuery.next()) {
            QVariantMap recordMap;
            QSqlRecord  record = selectQuery.record();
            int count = record.count();
            for (int i = 0; i < count; ++i) {
                QString fieldName = selectQuery.record().fieldName(i);
                recordMap[fieldName] = selectQuery.value(i);
            }
            T *obj = new T();
            obj->fromMap(recordMap);
            results.append(obj);
        }
        return results;
    }


private:
    QSqlDatabase db;

    QSqlQuery query;


};

#endif // SQLITEUTILS_H
